﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Threading;

namespace System
{
    /// <summary>
    /// 延迟推送.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class DelayNotificationHelper<T>
    {
        #region 属性

        /// <summary>
        /// 延迟计时器
        /// </summary>
        public Timer DelayTimer;

        /// <summary>
        /// 值
        /// </summary>
        private T _value;
        /// <summary>
        /// 获取或设置值.
        /// </summary>
        /// <value>值.</value>
        public T Value
        {
            get { return _value; }
            set
            {
                _value = value;
                DelayTimer.Stop();
                DelayTimer.Start();
            }
        }

        /// <summary>
        /// 延迟毫秒数
        /// </summary>
        private int delayMilliseconds;
        /// <summary>
        /// 获取或设置延迟推送毫秒数.
        /// </summary>
        /// <value>The delay milliseconds.</value>
        public int DelayMilliseconds
        {
            get { return delayMilliseconds; }
            set
            {
                delayMilliseconds = value;
                if (DelayTimer == null)
                {
                    DelayTimer = new Timer();
                }

                DelayTimer.Interval = value;
                DelayTimer.Elapsed -= DelayTimer_Elapsed;
                DelayTimer.Elapsed += DelayTimer_Elapsed;
            }
        }
        #endregion

        #region 事件

        /// <summary>
        /// 延迟推送通知委托.
        /// </summary>
        public event Action<T> OnNotifyValue;

        #endregion 

        #region 构造
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="delayMilliseconds"></param>
        public DelayNotificationHelper(int delayMilliseconds = 100)
        {
            DelayMilliseconds = delayMilliseconds;
        }

        #endregion

        #region 方法

        private void DelayTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            OnNotifyValue?.Invoke(Value);
            DelayTimer.Stop();
        }
        #endregion
    }
}